//
//  AddPictureViewController.swift
//  微博
//
//  Created by mac on 15/12/24.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let rowCount: CGFloat = 3
private let margin: CGFloat = 5
private let maxImageCount = 9

class AddPictureViewController: UICollectionViewController {
    
    var imageList = [UIImage]()
    
    init() {
        let flowLayout = UICollectionViewFlowLayout()
        //设置size
        let itemW = (screenWidth - (rowCount - 1) * margin) / 3
        flowLayout.itemSize = CGSize(width: itemW, height: itemW)
        flowLayout.minimumLineSpacing = margin
        flowLayout.minimumInteritemSpacing = margin
        super.init(collectionViewLayout: flowLayout)
        collectionView?.backgroundColor = UIColor.whiteColor()
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(AddPictureViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        
    }



    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let count = imageList.count == 9 ? 0 : 1
        return imageList.count + count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! AddPictureViewCell
    
        // Configure the cell
        cell.backgroundColor = UIColor.whiteColor()
        //遵守协议
        cell.delegate = self
        //设置数据源
        if imageList.count == indexPath.item {
            cell.image = nil
        }else {
            cell.image = imageList[indexPath.item]
        }
    
        return cell
    }
}

extension AddPictureViewController : AddPictureViewCellDelegate {
    func userChosePicture(cell: AddPictureViewCell) {
        if cell.image != nil {
            print("已经选择了图片")
            return
        }
        //创建一个图片控制器
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        //model一个图片选择控制器
        presentViewController(imagePicker, animated: true, completion: nil)
    }
    func userDelegatePicture(cell: AddPictureViewCell) {
        //把对应的cell的删除
        //获取选中的cellindex
        if let index = collectionView?.indexPathForCell(cell) {
            imageList.removeAtIndex(index.item)
            //刷新cell
            collectionView?.reloadData()
        }
    }
    
}

extension AddPictureViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //选择完图片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //把图片添加到数组中
        imageList.append(image)
        //刷新collecttion
        collectionView?.reloadData()
        //dismiss控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
}


//创建协议,去选择图片控制器
@objc protocol AddPictureViewCellDelegate :NSObjectProtocol {
    optional func userChosePicture(cell:AddPictureViewCell)
    optional func userDelegatePicture(cell:AddPictureViewCell)
}


//自定义cell
class AddPictureViewCell:UICollectionViewCell {
    
    //设置代理属性
    weak var delegate:AddPictureViewCellDelegate?
    
    var image: UIImage? {
        didSet{
            //设置图片,让删除按钮隐藏
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
            
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //点击事件
    @objc private func addBtnClick() {
        print(__FUNCTION__)
       //调用协议方法
        delegate?.userChosePicture?(self)
    }
    @objc private func deleteBtnClick() {
        print(__FUNCTION__)
        delegate?.userDelegatePicture?(self)
    }
    
    
    //设置UI
    private func setupUI() {
        addSubview(addBtn)
        addSubview(deleteBtn)
        //设置image的mode
        addBtn.imageView?.contentMode = .ScaleAspectFill
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(self.snp_right)
            make.top.equalTo(self.snp_top)
        }
        //设置点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
    }
    
    //懒加载控件
    private lazy var addBtn:UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
    private lazy var deleteBtn:UIButton = UIButton(imageName: nil, backImageName: "compose_photo_close")
    
}


